<template>
  <div class="knowledge-article-management">
    <!-- 搜索及筛选区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" ref="searchForm">
        <el-form-item label="文章状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable>
            <el-option
              v-for="item in articleStatusOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章搜索">
          <el-input
            v-model="searchForm.searchKeywords"
            placeholder="输入标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAddArticle"
            >添加文章</el-button
          >
        </el-form-item>
         <el-form-item>
          <el-button type="info" @click="handleSyncArticle">同步文章</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
      :border="false"
    >
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="文章名称"
        min-width="300"
        align="center"
      >
        <template #default="scope">
          <span class="clickable-title" @click="handleTitleClick(scope.row)">
            {{ scope.row.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="author"
        label="作者"
        min-width="50"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="文章状态"
        min-width="80"
        align="center"
      ></el-table-column>
      
      <el-table-column
        prop="createdTime"
        label="发布日期"
        min-width="120"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="460" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row, $event)"
            >查看</el-button
          >
          <el-button type="text" @click="handleEdit(scope.row, $event)"
            >编辑</el-button
          >
          <el-button
            type="text"
            :style="{ color: 'green' }"
            @click="handlePublish(scope.row, $event)"
            >发布</el-button
          >
          <el-button
            type="text"
            :style="{ color: 'orange' }"
            @click="handleOffline(scope.row, $event)"
            >下线</el-button
          >
          <el-button
            type="text"
            :style="{ color: 'red' }"
            @click="handleDelete(scope.row, $event)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: "KnowledgeArticleManagement",
  data() {
    return {
      searchForm: {
        articleType: "",
        status: "",
        searchKeywords: "",
      },

      // 文章状态选项
      articleStatusOptions: [],
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
    };
  },
  created() {
    this.fetchTableData();
    this.initTypeOptions();
  },
  methods: {
    async fetchDeliveryOptions(type) {
      this.optionsLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(
          `/trade/carbonTradeQuote/getDeliveryMethod/${type}`
        );
        if (res.code == 200) {
          return res.data; // 返回查询到的列表
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },
    async initTypeOptions() {
      // 1. 获取文章状态
      const modes = await this.fetchDeliveryOptions("status");
      this.articleStatusOptions = modes;
    },
    // 标题点击跳转（保持原逻辑）
    handleTitleClick(row) {
      if (row.url) {
        window.open(row.url, "_blank");
      } else {
        this.$message.warning("该文章没有关联的URL");
      }
    },
 async handleSyncArticle() {
    // try {
    //   const res = await this.$request.get("/system/carbonArticle/sync-article");
    //   if (res.code === 200) {
    //     this.$message.success("文章同步操作执行成功");
    //     // 同步成功后，可重新获取表格数据，更新页面显示
    //     this.fetchTableData(); 
    //   } else {
    //     this.$message.error("文章同步操作执行失败，请重试");
    //   }
    // } catch (error) {
    //   console.error("调用同步文章接口失败:", error);
    //   this.$message.error("网络异常，请重试");
    // }
     const syncUrl = "http://localhost:9091/system/carbonArticle/sync-article"; 
  window.location.href = syncUrl;
  },
    // 查看操作：跳转到行数据的url地址
    handleView(row, event) {
      const button = document.activeElement;
     
      window.open(row.url, "_blank"); 
      if (button && button.blur) {
        // 延迟执行，确保跳转逻辑完成后再失焦
        setTimeout(() => {
          button.blur();
          // 额外措施：将焦点移到文档body，避免残留焦点问题
          document.body.focus();
        }, 100);
      }
    },

    // 编辑操作：跳转到行数据的url地址
    handleEdit(row, event) {
      const button = document.activeElement;
      // 这里假设 row 有 editUrl 属性存储编辑页面地址，若实际是跳转到其他地址可自行调整
      const editUrl = row.url;
      if (editUrl) {
        window.open(editUrl, "_blank");
      } else {
        this.$message.warning("该文章没有关联的编辑URL");
      }
      if (button && button.blur) {
        // 延迟执行，确保跳转逻辑完成后再失焦
        setTimeout(() => {
          button.blur();
          // 额外措施：将焦点移到文档body，避免残留焦点问题
          document.body.focus();
        }, 100);
      }
    },
    // 获取表格数据
    async fetchTableData() {
      this.tableLoading = true;
      try {
        const res = await this.$request.post("/system/carbonArticle/search", {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm,
        });
        if (res.code === 200) {
          this.tableData = res.data.list;
          this.totalCount = res.data.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.tableLoading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 收藏操作
    handleCollect(row) {
      const button = document.activeElement;
      this.$confirm("请进入飞书文档，点击标题右侧按钮收藏！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          this.handleTitleClick(row);
        })
        .catch(() => {})
        .finally(() => {
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },

    // 添加文章
    // 修改 handleAddArticle 方法
    handleAddArticle() {
      // 1. 调用后端创建接口
      this.$request
        .post("/system/carbonArticle/create-feishu-doc", {
          // 若接口需要参数，可在此补充（根据实际需求传参）
          // 如：articleType: 'xxx'
        })
        .then((res) => {
          console.log("dada",res)
          if (res.code === 200) {
            const feishuUrl = res.msg; // 假设接口返回的飞书编辑地址存在 res.data.url
            if (feishuUrl) {
              // 2. 跳转飞书编辑页面
              window.open(feishuUrl, "_blank");
            } else {
              this.$message.warning("未获取到飞书文章 URL");
            }
          } else {
            this.$message.error("创建飞书文章失败，请重试");
          }
        })
        .catch((error) => {
          console.error("调用创建接口失败:", error);
          this.$message.error("网络异常，请重试");
        });
    },

    
    // 发布操作
    handlePublish(row, event) {
      // 接收$event参数
      const button = document.activeElement; // 记录当前点击的按钮
      this.$confirm(`确定要发布文章【${row.title}】吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/system/carbonArticle/offlineOrPublish",
              { id: row.id, status: row.status }
            );
            if (res.code === 200) {
              this.$message.success("发布成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("发布失败:", error);
            this.$message.error("发布失败，请重试");
          }
        })
        .finally(() => {
          // 无论确认/取消，都执行失焦处理
          if (button && button.blur) {
            setTimeout(() => {
              button.blur(); // 移除按钮焦点
              document.body.focus(); // 将焦点转移到body，避免残留
            }, 100);
          }
        });
    },

    // 下线操作
    handleOffline(row, event) {
      // 接收$event参数
      const button = document.activeElement; // 记录当前点击的按钮
      this.$confirm(`确定要下线文章【${row.title}】吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/system/carbonArticle/offlineOrPublish",
              { id: row.id, status: row.status }
            );
            if (res.code === 200) {
              this.$message.success("下线成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("下线失败:", error);
            this.$message.error("下线失败，请重试");
          }
        })
        .finally(() => {
          // 无论确认/取消，都执行失焦处理
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },

    // 删除操作
    handleDelete(row, event) {
      // 接收$event参数
      const button = document.activeElement; // 记录当前点击的按钮
      this.$confirm(
        `确定要删除文章【${row.title}】吗？删除后不可恢复`,
        "提示",
        {
          type: "error",
        }
      )
        .then(async () => {
          try {
            const res = await this.$request.post(
              "/system/carbonArticle/delete",
              {
                id: row.id,
              }
            );
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.fetchTableData();
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败，请重试");
          }
        })
        .finally(() => {
          // 无论确认/取消，都执行失焦处理
          if (button && button.blur) {
            setTimeout(() => {
              button.blur();
              document.body.focus();
            }, 100);
          }
        });
    },
  },
};
</script>

<style scoped>
.clickable-title {
  cursor: pointer;
  transition: color 0.2s;
}

.clickable-title:hover {
  color: #66b1ff;
}
.knowledge-article-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-section {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.operation-btns {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  width: 100%;
}
</style>
